/**************************************************START OF FILE*****************************************************/






/*------------------------------------------------------------------------------------------------------------------
Includes
*/
#include "xBSP_Gpio.h"
#include "xSYS_KeyScan.h"


/*------------------------------------------------------------------------------------------------------------------
Macros
*/



/*------------------------------------------------------------------------------------------------------------------
Variables
*/
static  uint32_t KeyCanChange;
static  uint32_t KeyNoChangedTime = 0;
/*Key Status*/
static  uint32_t KeyCurrent = 0, KeyOld = 0 ;
static  uint32_t KeyPress = 0, KeyDown = 0, KeyUp = 0, KeyLast = 0;

pFunCallback pKeyEventCallback = NULL;


/*------------------------------------------------------------------------------------------------------------------
Functions
*/


/*
********************************************************************************************************************
@ Brief  : 注册按键事件处理回调函数

@ Param  : None

@ Return : None

@ Author : LYC

@  Date  : 2020 - 04 - 03
********************************************************************************************************************
*/
bool xSYS_KeyScan_RegisterCallback(pFunCallback pfun)
{	
    if(NULL == pKeyEventCallback)
    {
        pKeyEventCallback = pfun;
        KeyCanChange = 1;
        return true;
    }
    else
    {
        KeyCanChange = 0;
        return false;
    }
}

/*
********************************************************************************************************************
@ Brief  : 按键状态扫描

@ Param  : None

@ Return : None

@ Author : LYC

@  Date  : 2020 - 04 - 03
********************************************************************************************************************
*/
void xSYS_KeyScan(void)
{
	static uint32_t keyUpClearFlag = 0;//用于清除弹起消息
	KEY_Message_TypeDef KeyMessage;

	if(!KeyCanChange)return;

	/*************************获取按键值***********************/
	KeyCurrent = xBSP_IO_Input_GetData();

	if(KeyCurrent != KeyOld)
	{
		KeyNoChangedTime = 0;
		KeyOld = KeyCurrent;
		return;	
	}
	else	
	{
		KeyNoChangedTime++;
		if(KeyNoChangedTime >= 1)
		{
			KeyNoChangedTime = 1;
		
			KeyPress = KeyOld;
			KeyDown |= (~KeyLast) & (KeyPress);
			KeyUp |= KeyLast & (~KeyPress);
			KeyLast = KeyPress;		
		}
	}

	////////////////////电源按键长按//////////////////////

	//搜集按键消息
	KeyMessage.KeyDown = KeyDown;
	KeyMessage.KeyUp = KeyUp;
	KeyMessage.KeyPress = KeyPress;

    /*按键事件处理回调*/
    (*pKeyEventCallback)(&KeyMessage);

    KeyDown = 0;
    KeyUp = 0;
	KeyPress = 0;
}

/****************************************************END OF FILE*****************************************************/

